/**
 * zmn文章模块-文章编辑
 * 文件命名格式：zmn.模块.表/功能.jas
 * @author heguanghua
 * @since 2018/10/18
 */
var form = null;

layui.define(['form', 'layedit', 'laydate'], function (exports) {
    let $ = layui.$;
    form = layui.form;
    let layer = layui.layer;
    let index;

    form.verify({
        minSort: function(value, item){ //value：表单的值、item：表单的DOM对象
            if (value < 1){
                return "排序号不能小于1";
            }
            if (value > 10000000){
                return "排序号不能大于10000000";
            }
        }, isPositiveNumber: function(value,item){
            if (!/^[0-9]+$/.test(value)) {
                return "排序值只能是正整数";
            }
        },tariffName:function (value) {
            if(!/^[A-Za-z0-9\u4e00-\u9fa5]+$/.test(value)){
                return "计价器名称只能输入字母、数字、汉字";
            }
        }
    });

    zmnLayUtil.layFormVerify(form);

    form.render(null, "zmn-form");

    // 提交
    form.on('submit(zmn-form-submit)', function (obj) {
        let data = obj.field;
        data['deptOneName'] = $('#oneDeptId option:selected').text();
        data['deptTwoName'] = $('#deptId option:selected').text()
        let url = "/standard/record/addEditDetail.action";
        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json", dataType: "json", data: JSON.stringify(data),
            beforeSend: function () {
                index = layer.load(1, {
                    shade: [0.5, '#DBDBDB']
                });
            },
            success: function (json) {
                layer.close(index);
                layer.msg(json.message);
                if (json.status == 200) {
                    setTimeout(function () {
                        window.location.href="/standard/record/content.action?standardId="+json.data;
                    },1000);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            },
            complete:function () {
                layer.close(index);
            }
        })

        return false;
    });

    // 2级部门联动
    form.on('select(oneDeptId)', function(obj){
        triggerTwoDeptOptions(obj.value);
    })

    function triggerTwoDeptOptions(value){
        let twoDeptOptions = json.twoDepts.filter(p => p.parentId == value).map(p => {
            return p.deptId == json.standardRecord.deptTwoId ? '<option value="'+p.deptId+'" selected="selected">'+p.deptName+'</option>' : '<option value="'+p.deptId+'">'+p.deptName+'</option>';
        });
        twoDeptOptions.unshift('<option value=""></option>');
        $('#deptId').html(twoDeptOptions);
        form.render("select");
    }

    //对外暴露的接口
    exports('standard_record_detail_edit_js', {});
});

